
function hide_spectrum_annotation(){
        $("#spectrum_annotation_form").hide();
	myLayout.close('east');
	myLayout.close('west');
}

function delete_spectrum_annotation(id){
	new Messi('Are you sure you want to delete the selected Spectrum Annotation, id ' + id + '?', {title: 'Buttons', buttons: [{id: 0, label: 'Yes', val: 'Y'}, {id: 1, label: 'No', val: 'N'}], 
		callback: function(val) { if (val == 'Y'){ 
				archive_spectrum_annotation(id);
			}}});
}

function update_spectrum_annotation(id){
	new Messi('Applying existing spectrum annotation values to form fields, click Update when ready', {title:'Message'});
	for (arr in spectrum_annotation_arr){
        	var idfunc = spectrum_annotation_arr[arr][7];
		if (idfunc == id){
   			$("#spa_peak_mz").val(spectrum_annotation_arr[arr][0]);
        		$("#spa_formula").val(spectrum_annotation_arr[arr][1]);
        		$("#spa_inchi").val("");
			if (spectrum_annotation_arr[arr][4] != null && spectrum_annotation_arr[arr][4] != "None"){
			    document.getElementById("spa_confirm").checked = true;
			}
			if (spectrum_annotation_arr[arr][3] != null && spectrum_annotation_arr[arr][3] != "None"){
			    $("#spa_precursor_atoms_retained").val(spectrum_annotation_arr[arr][3]);
			}
        		$("#spa_comment").val(spectrum_annotation_arr[arr][5]);
        		$("#spa_isotope_max_mass").val(spectrum_annotation_arr[arr][2]);
        		$("#spa_pstructure").html("");
        		$("#spa_structure_container").css("display", "none");
			selectedspa = id;
		}
	}
	$("#newSpaButton").val("update");
	$("#newSpaButton").html("Update");
}


var selectedspa = -1;

function associate_spectrum_annotation(){
        if (spectrumAnnotationTable != undefined)
                spectrumAnnotationTable.fnClearTable();
	var spa_peak_mz = $("#spa_peak_mz").val();
        var spa_formula = $("#spa_formula").val();
 	var spa_inchi = $("#spa_inchi").val();
	var spa_comment = $("#spa_comment").val();
	var spa_max_mass = $("#spa_isotope_max_mass").val();
	var spa_confirm = 'f';
	if (document.getElementById("spa_confirm").checked == true){
		spa_confirm = 't';
	}
	var precursor_atoms_retained = $("#spa_precursor_atoms_retained").val();
	var ops = $("#newSpaButton").val();
	var spaid = selectedspa;
	if (spa_max_mass == ""){
	new Messi('Fragments without m/z range (MMI blank) will not show up in the MID library. Are you sure?', {title: 'Warning', buttons: [{id: 0, label: 'Yes', val: 'Y'}, {id: 1, label: 'No', val: 'N'}],
	        callback: function(val) { if (val == 'Y'){
	$("#compound_library_dialog").html("<img src='images/demo_wait.gif' />");
        $.ajax({
        	type: "POST",
                url:  "/cgi-bin/metabobase/update_spectrum_annotations.cgi",
                data: {
                'compound_id': $("#compound_id").val(),'spa_peak_mz': spa_peak_mz, 'spa_formula':spa_formula, 'spa_inchi':spa_inchi, 'spa_comment':spa_comment, 'spa_isotope_max_mass':spa_max_mass, 'spa_confirm':spa_confirm, 'precursor_atoms_retained':precursor_atoms_retained, 'spa_id':selectedspa, 'ops':ops
                                },
                                success: function(json)
                                {
                                        var jo  = $.parseJSON(json);
					$("#compound_library_dialog").hide();
					new Messi('Spectrum annotation added/updated successfully', {title: 'Info', autoclose: 1500});
                                        $("#compound_form_msg").html("Spectrum annotation added/updated for compound " + $("#compound_id").val() + " mz " + $("#spa_peak_mz").val());
                                	
					var spaid = jo["_spaid"];
					if (ops == "add"){
					    refresh_spectrum_annotation_list("Insert", spaid);
					}
					if (ops == "update"){
                                            refresh_spectrum_annotation_list("Update", spaid);
                                        }
					reset_spectrum_annotation_form();
				},
                                error:function(xhr,err)
                                {
                                        alert("Failed post\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });
		}
	}
	});
	}else{
		$("#compound_library_dialog").html("<img src='images/demo_wait.gif' />");
                $.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/update_spectrum_annotations.cgi",
                data: {
                'compound_id': $("#compound_id").val(),'spa_peak_mz': spa_peak_mz, 'spa_formula':spa_formula, 'spa_inchi':spa_inchi, 'spa_comment':spa_comment, 'spa_isotope_max_mass':spa_max_mass, 'spa_confirm':spa_confirm, 'precursor_atoms_retained':precursor_atoms_retained, 'spa_id':selectedspa, 'ops':ops
                                },
                                success: function(json)
                                {
                                        var jo  = $.parseJSON(json);
                                        $("#compound_library_dialog").hide();
                                        new Messi('Spectrum annotation added/updated successfully', {title: 'Info', autoclose: 1500});
                                        $("#compound_form_msg").html("Spectrum annotation added/updated for compound " + $("#compound_id").val() + " mz " + $("#spa_peak_mz").val());

                                        var spaid = jo["_spaid"];
					if (ops == "add"){
					    refresh_spectrum_annotation_list("Insert", spaid);
					}
					if (ops == "update"){
					    refresh_spectrum_annotation_list("Update", spaid);
					}
                                        reset_spectrum_annotation_form();
                                },
                                error:function(xhr,err)
                                {
                                        alert("Failed post\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });        
	}
}

function archive_spectrum_annotation(spaid){
        if (spectrumAnnotationTable != undefined)
                spectrumAnnotationTable.fnClearTable();
        $("#compound_library_dialog").html("<img src='images/demo_wait.gif' />");
        $.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/archive_metabobase.cgi",
                data: { 'spectrum_annotation_id': spaid, 'datatype':'spectrum_annotation'},
                                success: function(json)
                                {
                                        $("#compound_library_dialog").hide();
                                        $("#compound_form_msg").html("Spectrum annotation Archived spectrum annotation id " + spaid);
                                        refresh_spectrum_annotation_list("Archive", spaid);
                                        reset_spectrum_annotation_form();
                                },
                                error:function(xhr,err)
                                {
                                        alert("Failed post\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });
}

function reset_spectrum_annotation_form(){
	$("#spa_peak_mz").val("");
        $("#spa_formula").val("");
        $("#spa_inchi").val("");
	$("#spa_precursor_atoms_retained").val("");
        $("#spa_comment").val("");
        $("#spa_isotope_max_mass").val("");
	document.getElementById("spa_confirm").checked = false;
	$("#spa_pstructure").html("");
	$("#spa_structure_container").css("display", "none");
	pre_sif_loaded = 0;
	$("#newSpaButton").val("add");
	$("#newSpaButton").html("Add");

}


function findAndRemove(array, property, value) {
   $.each(array, function(index, result) {
      if(result[property] == value) {
          //Remove from array
          array.splice(index, 1);
      }    
   });
}

function refresh_spectrum_annotation_list(ops, mz){
	var annos = {};
	var addedSpAnno = [];
	if (ops == "Insert"){
        	addedSpAnno.push($("#spa_peak_mz").val());
        	addedSpAnno.push($("#spa_formula").val());
        	addedSpAnno.push($("#spa_isotope_max_mass").val());
		var spa_confirm = "False";
		if (document.getElementById("spa_confirm").checked == true){
			spa_confirm = "True";
		}
		addedSpAnno.push($("#spa_precursor_atoms_retained").val());
		addedSpAnno.push(spa_confirm);
		addedSpAnno.push($("#spa_comment").val());
        	addedSpAnno.push("<a href=javascript:update_spectrum_annotation('" + mz + "')>Update&nbsp;</a>" + "<a href=javascript:delete_spectrum_annotation('" + mz + "')>Delete</a>");
		spectrum_annotation_arr.push(addedSpAnno);
	}
	if (ops == "Update"){
                for (arr in spectrum_annotation_arr){
                        var idfunc = spectrum_annotation_arr[arr][6];
                        if (idfunc.indexOf(""+mz) != -1){
                              addedSpAnno.push($("#spa_peak_mz").val());
		              addedSpAnno.push($("#spa_formula").val());
                	      addedSpAnno.push($("#spa_isotope_max_mass").val());
                	      var spa_confirm = "False";
                              if (document.getElementById("spa_confirm").checked == true){
                        	spa_confirm = "True";
                	      }
                	      addedSpAnno.push($("#spa_precursor_atoms_retained").val());
                	      addedSpAnno.push(spa_confirm);
                	      addedSpAnno.push($("#spa_comment").val());
                	      addedSpAnno.push("<a href=javascript:update_spectrum_annotation('" + mz + "')>Update&nbsp;</a>" + "<a href=javascript:delete_spectrum_annotation('" + mz + "')>Delete</a>");
	 
			      spectrum_annotation_arr[arr] = addedSpAnno;
                              break;
			}
                }
        }
	if (ops == "Archive"){
		//find index to remove
		var ind = 0;
		for (arr in spectrum_annotation_arr){
			var idfunc = spectrum_annotation_arr[arr][6];
			if (idfunc.indexOf(""+mz) != -1){			
			//if (spectrum_annotation_arr[arr][0] == mz){				
				break;
			}
			ind++;
		}
		spectrum_annotation_arr.splice(ind, 1);
	}
        spectrumAnnotationTable = $('#spectrum_annotation_tbl').dataTable( {
                        "bProcessing": true,
                        "bDestroy": true,
                        'bPaginate':false,
                        'bInfo':false,
                        'bFilter':false,
                        "aaData": spectrum_annotation_arr,
                        fnDrawCallback: function() {
                                dblclickSpectrumAnnotation();
                        }
        } );
}

function show_spectrum_annotation_form(sparr){
	pre_sif_loaded = 0;
	myLayout.close('west');
	var addSpectrum = "<br><a href=javascript:show_compound_form('current')><font size='-2'>View Compound</font></a>&nbsp;<a href=javascript:show_spectrum_form(null)><font size='-2'>Add Spectrum</font></a>";
	$("#compound_form_msg").html($("#compound_name").val() + " (" + $("#compound_id").val() + ")<br>" + "Formula:" + $("#sum_formula").val() + " Nominal Mass:" + $("#nominal_mass").val() + addSpectrum);
        $("#spectrum_annotation_form").show();
	$("#spectrum_form").hide();
        $("#compound_form").hide();
	reset_spectrum_annotation_form();
	processCompoundSpectrum("compound_spectral_tbl", "spectrum_annotation_tbl", $("#compound_id").val());
}

function load_structure(){
	if (pre_sif_loaded == 1){
		return;
	}
	
	var pid = "";
        var precursor_name = "";//$("#compound_precursor").val();
	if (compound_precursor_arr == null || compound_precursor_arr.length < 1){
	// precursor_name == null || precursor_name == ""){
		return;
	}else{
		$("#spa_formula_span").html("");
		precursor_name = compound_precursor_arr[0][0];
		/*var pre_links = "";	
		for (var pi = 0; pi< compound_precursor_arr.length; pi++){
			pre_links = pre_links + "&nbsp;" + '<a href="#" onclick="reload_structure(\'' + compound_precursor_arr[pi][1] +'\');">' + compound_precursor_arr[pi][0] + '</a>';	
		}
		$("#spa_formula_span").html(pre_links);*/
	}
	for (var c in compound_dictionary){
                if (compound_dictionary[c] == precursor_name){
                        pid = c;
                        break;
                }
        }
	$("#spa_structure_container").css("display", "block");
	$("#spa_structure_container").css("height", "250");
	$("#spa_structure_container").html("Loading... <img src='images/demo_wait.gif' />");
	$("#spa_pstructure").html("Precursor: " + precursor_name + " ID " + pid);
	metabobase_session["pid"] = pid;
	if (pre_sif_loaded == 0){
		visSifLoad("#spa_structure_container");
	}
}

function reload_structure(pid){

        $("#spa_structure_container").css("display", "block");
        $("#spa_structure_container").css("height", "250");
        $("#spa_structure_container").html("Loading... <img src='images/demo_wait.gif' />");
        $("#spa_pstructure").html("Precursor: " + precursor_name + " ID " + pid);
        metabobase_session["pid"] = pid;
        visSifLoad("#spa_structure_container");
}


